import { getToken, removeToken, setToken } from '@/utils/auth'
import { login, getProfile, getUserDetailById } from '@/api/user'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      // 存储到cookies中做持久化
      setToken(token)
    },
    clearToken(state) {
      state.token = ''
      // 清除cookies中Token
      removeToken()
    },
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    reomveUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async userLogin(context, formData) {
      console.log(context, 'context')
      const res = await login(formData)
      console.log('ok2222')
      console.log('登录成功获取到结果-->token', res.data)
      context.commit('updateToken', res.data)
    },
    async getUserInfo(context) {
      const res = await getProfile()
      console.log(res, 'getProfile')
      const info = await getUserDetailById(res.data.userId)
      console.log(info.data, 'getUserDetailById')
      context.commit('updateUserInfo', { ...res.data, ...info.data })
    },
    logout(context) {
      context.commit('clearToken')
      context.commit('reomveUserInfo')
    }
  }
}
